<template>
  <div class="carousel">
    <div class="slider" ref="slider" @transitionend="handleTransitionEnd">
      <div class="slides" :style="{ transform: `translateX(-${currentSlideIndex * 100}%)` }">
        <div 
          v-for="(slide, index) in slides" 
          :key="index" 
          class="slide" 
          :class="{ active: currentSlideIndex === index }"
        >
          <img :src="slide.imageUrl" alt="" style="width: 100%; height: 100%; object-fit: cover;">
        </div>
      </div>
    </div>
    <div class="dots" v-if="slides.length > 1">
      <button
        v-for="(slide, index) in slides"
        :key="index"
        class="dot"
        :class="{ active: currentSlideIndex === index }"
        @click="goToSlide(index)"
      ></button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';

const slides = [
  {
    imageUrl: 'https://www.jiakaobaodian.com/core-assets/static/images/common/home_banner_jiaxiaobang.png'
  },
  {
    imageUrl: 'https://www.jiakaobaodian.com/core-assets/static/images/common/home_banner_download.png'
  },
  {
    imageUrl: 'https://www.jiakaobaodian.com/core-assets/static/images/common/home_banner_new1.jpeg'
  },
  {
    imageUrl: 'https://www.jiakaobaodian.com/core-assets/static/images/common/home_banner_jiaolian.jpg'
  }
];

const slider = ref(null);
const currentSlideIndex = ref(0);

const goToSlide = (index) => {
  currentSlideIndex.value = index;
};

// 自动切换函数
const startAutoSwitch = () => {
  const switchInterval = setInterval(() => {
    currentSlideIndex.value = (currentSlideIndex.value + 1) % slides.length;
    // 确保每次切换都触发过渡效果
    slider.value.style.transform = `translateX(-${currentSlideIndex.value * 100}%)`;
  }, 4000);

  return switchInterval; // 返回定时器句柄以便清除
};

onMounted(() => {
  // 启动自动切换，并保存定时器句柄
  autoSwitchInterval = startAutoSwitch();
});

onUnmounted(() => {
  // 组件卸载时清除定时器
  clearInterval(autoSwitchInterval);
});

let autoSwitchInterval; // 定义在外部以供onUnmounted访问
</script>

<style scoped>
.carousel {
  position: relative;
  width: 900px; /* 设置轮播图宽度 */
  height: 380px; /* 设置轮播图高度 */
  overflow: hidden;
}

.slider {
  width: 100%;
  height: 100%; 
  position: relative;
}

.slides {
  display: flex;
  transition: transform 0.1s ease-in-out;
  width: 100%;
  height: 10%;
  position: absolute;
}

.slide {
  width: 100%;
  height: 10%;
  position: relative;
  opacity: 0;
  transition: opacity 0.1s ease-in-out;
}

.slide img {
  width: 100%;
  height: 10%;
  object-fit: cover;
}

.slide.active {
  opacity: 1;
}

.dots {
  text-align: center;
  margin-top: 1rem;
}

.dot {
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color: #ccc;
  border-radius: 50%;
  margin: 0 5px;
  cursor: pointer;
}

.dot.active {
  background-color: #000;
}
</style>